#include <bits/stdc++.h>
#define Fill(a, b) memset(a, b, sizeof(a))
#define Assign(a, b) memcpy(&a, &b, sizeof(a))
#define equal(a, b) memcmp(a, b, sizeof(a))==0
using namespace std;
const int maxs = 400000;
typedef int state[9];
state goal = {1, 2, 3, 8, 0, 4, 7, 6, 5};
state buf[maxs];
int D[maxs], front, rear;


//set<int> S;
int Hash(state &s){
    int v=0;
    for (int j = 0; j < 9; ++j) {
        v = v*10 + s[j];
    }
    return v % maxs;
}


int head[maxs], Next[maxs];
bool Vis(int i){
    int h = Hash(buf[i]);
    int u = head[h];
    while(u){
        if(equal(buf[u], buf[i])) return true;
        u = Next[u];
    }
    Next[i] = head[h];
    head[h] = i;
    return false;
}
//
//bool vis(state &sta){
//    int i=0;
//    for (int j = 0; j < 9; ++j) {
//        i+= pow(10, j) * sta[j];
//    }
//    if(S.count(i)) return true;
//    else{
//        S.insert(i); return false;
//    }
//}

int dx[] = {1, -1, 0, 0};
int dy[] = {0, 0, 1, -1};
void bfs(){
    front = 1; rear = 2;
    Fill(D, -1); D[1] = 0;
    Fill(Next, 0); Fill(head, 0);
    while(front < rear){
        state &s = buf[front];
        if(memcmp(s, goal, sizeof(s)) == 0) {cout << D[front]; return;}

        int map[3][3]; for(int i=0; i<9; ++i) map[i/3][i%3] = s[i];
        int z; for(z = 0; z<9; ++z) if(!s[z]) break;
        int x = z / 3, y = z % 3;

        for (int i = 0; i < 4; ++i) {
            int x2 = x+dx[i], y2 = y + dy[i];
            if(x2>=0 && x2<3 && y2>=0 && y2<3){
                int z2 = x2 * 3 + y2;
                state nex; Assign(nex, s);
                swap(nex[z], nex[z2]);

                D[rear] = D[front] + 1;
                Assign(buf[rear], nex);
                if(!Vis(rear)) ++rear;
            }
        }
        ++front;
    }
}
int main() {
    ios_base::sync_with_stdio(false);cin.tie(nullptr);
    string in;
    cin >> in;
    for (int i = 0; i < 9; ++i) {
        buf[1][i] = in[i] - '0';
    }
    bfs();
    return 0;
}